package com.roxas.nfc.test;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.os.Parcelable;
import android.telephony.SmsManager;
import android.view.Menu;
import android.widget.Toast;

import com.google.common.base.Charsets;
import com.google.common.primitives.Bytes;
import com.roxas.nfc.R;
import com.roxas.nfc.R.layout;
import com.roxas.nfc.R.menu;

public class CopyOfMainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void writeNdefTag(Intent in) {
		Tag tag = in.getParcelableExtra(NfcAdapter.EXTRA_TAG);
		Ndef ndef = Ndef.get(tag);
		try {

			// 这一句别丢了，读nfc标签的时候不需要这句，因为那时数据直接就在intent中。
			ndef.connect();

			// 构造一个合适的NdefMessage。你可以看到代码里用了NdefRecord数组，只不过这个数组里只有一个record

			NdefMessage ndefMsg = new NdefMessage(new NdefRecord[] { createRecord() });
			ndef.writeNdefMessage(ndefMsg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void writeNdefTag2(Intent in) {
		Tag tag = in.getParcelableExtra(NfcAdapter.EXTRA_TAG);// 先取出TAG
		// NfcA nfcA = NfcA.get(tag);
		// nfcA.getAtqa();
		// String content1 = new String(nfcA.getAtqa());
		Ndef ndef = Ndef.get(tag);// 从TAG中取出NDEF
		// MifareClassic mfc = MifareClassic.get(tag);

		// ---------------这段代码第一次执行要注释 因为没有写入过的卡，ndef是空的。-------------------
		Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);// 取出NDEF里的messages
		NdefMessage msg = (NdefMessage) rawMsgs[0];// 取第一个message；
		String content = new String(msg.getRecords()[0].getPayload());// 将第一个message里的第一个record的playroad取出来，转成STRING；
		System.err.println(content);
		String phone_number = "你要发送手机号码（18888888888）";
		// 以下是发短信代码；
		SmsManager smsManager = SmsManager.getDefault();
		if (content.length() > 70) {
			List<String> contents = smsManager.divideMessage(content);
			for (String sms : contents) {
				smsManager.sendTextMessage(phone_number, null, sms, null, null);
			}
		} else {
			smsManager.sendTextMessage(phone_number, null, content, null, null);
		}
		Toast.makeText(this, "发送成功！", Toast.LENGTH_SHORT).show();
		// ---------------这段代码第一次执行要注释 因为没有写入过的卡，ndef是空的。-------------------

		// ----------以下是写入代码----------写入过程手机不能离开nfc tag，直到写入完成。
		Locale locale = Locale.CHINESE;
		final byte[] langBytes = locale.getLanguage().getBytes(Charsets.UTF_8);
		String text = "我安全到家了!";// 你要发送的短信文字。
		final byte[] textBytes = text.getBytes(Charsets.UTF_8);
		final int utfBit = 0;
		final char status = (char) (utfBit + langBytes.length);
		final byte[] data = Bytes.concat(new byte[] { (byte) status }, langBytes, textBytes);
		NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
		try {
			NdefRecord[] records = { record };
			// ,NdefRecord.createApplicationRecord("com.roxas.nfc")
			NdefMessage message = new NdefMessage(records);
			ndef.connect();
			ndef.writeNdefMessage(message);
			Toast.makeText(this, "写入成功！", Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// ----------以下是写入代码----------写入过程手机不能离开nfc tag，直到写入完成。第二次执行代码 注释这段就行了。
	}

	private NdefRecord createRecord() {
		return new NdefRecord(NdefRecord.TNF_ABSOLUTE_URI, "http://www.sohu.com".getBytes(Charset.forName("US-ASCII")), new byte[0], new byte[0]);

		// return new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
		// "application/com.android.TestNfc".getBytes(Charset.forName("US-ASCII")),
		// new byte[0],
		// "com.android.yufeimusic".getBytes(Charset.forName("US-ASCII")));
	}

	@Override
	protected void onResume() {

		NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
		int requestCode = 0;
		int flags = 0;
		Intent intent = new Intent(this, getClass());
		intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, flags);
		IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
		IntentFilter[] intentFilters = new IntentFilter[] { intentFilter };
		String[][] techLists = new String[][] { new String[] { Ndef.class.getName() } };
		adapter.enableForegroundDispatch(this, pendingIntent, intentFilters, techLists);

		//可以在activity在前台时，独占nfc处理
		
		
		// 如果应用捕捉到tag信息会从onResume开始执行 TAG信息的处理过程。
		Tag tag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
		if (tag == null) {// 如果tag为空我们就不处理。
			super.onResume();
			return;
		}
		// writeNdefTag(getIntent());
		writeNdefTag2(getIntent());// 处理Tag
		// Parcelable[] rawMsgs =
		// getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
		// // only one message sent during the beam
		// NdefMessage msg = (NdefMessage) rawMsgs[0];
		// new String(msg.getRecords()[0].getPayload());
		// // record 0 contains the MIME type, record 1 is the AAR, if present
		// // 取出封装在intent中的TAG
		// Tag tagFromIntent =
		// getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
		// for (String tech : tagFromIntent.getTechList()) {
		// System.out.println(tech);
		// }
		// boolean auth = false;
		// // 读取TAG
		// MifareClassic mfc = MifareClassic.get(tagFromIntent);
		// try {
		// String metaInfo = "";
		// // Enable I/O operations to the tag from this TagTechnology object.
		// mfc.connect();
		// int type = mfc.getType();// 获取TAG的类型
		// int sectorCount = mfc.getSectorCount();// 获取TAG中包含的扇区数
		// String typeS = "";
		// switch (type) {
		// case MifareClassic.TYPE_CLASSIC:
		// typeS = "TYPE_CLASSIC";
		// break;
		// case MifareClassic.TYPE_PLUS:
		// typeS = "TYPE_PLUS";
		// break;
		// case MifareClassic.TYPE_PRO:
		// typeS = "TYPE_PRO";
		// break;
		// case MifareClassic.TYPE_UNKNOWN:
		// typeS = "TYPE_UNKNOWN";
		// break;
		// }
		// metaInfo += "卡片类型：" + typeS + "\n共" + sectorCount + "个扇区\n共" +
		// mfc.getBlockCount() + "个块\n存储空间: " + mfc.getSize() + "B\n";
		// for (int j = 0; j < sectorCount; j++) {
		// // Authenticate a sector with key A.
		// auth = mfc.authenticateSectorWithKeyA(j, MifareClassic.KEY_DEFAULT);
		// int bCount;
		// int bIndex;
		// if (auth) {
		// metaInfo += "Sector " + j + ":验证成功\n";
		// // 读取扇区中的块
		// bCount = mfc.getBlockCountInSector(j);
		// bIndex = mfc.sectorToBlock(j);
		// for (int i = 0; i < bCount; i++) {
		// byte[] data = mfc.readBlock(bIndex);
		// metaInfo += "Block " + bIndex + " : " + bytesToHexString(data) +
		// "\n";
		// bIndex++;
		// }
		// } else {
		// metaInfo += "Sector " + j + ":验证失败\n";
		// }
		// }
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		super.onResume();
	}

	// 字符序列转换为16进制字符串
	private String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("0x");
		if (src == null || src.length <= 0) {
			return null;
		}
		char[] buffer = new char[2];
		for (int i = 0; i < src.length; i++) {
			buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
			buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
			System.out.println(buffer);
			stringBuilder.append(buffer);
		}
		return stringBuilder.toString();
	}
}
